<?php

/* $querystring = parse_url('http://mp3.zing.vn/album/Dut-Tung-Doan-Ruot-Luong-Bich-Huu/ZWZAE6EA.html', PHP_URL_QUERY);

parse_str($querystring, $vars);

echo '<pre>';

print_r($vars);

echo '</pre>'; */



if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

	require_once 'libraries/function/validateAjax.php';
	$data = array();
	if($_GET['validateTitle'] == 1){

		$validateAjax = new ValidateAjax();

		$validateAjax->validateTitle($_POST['txtTitle']);

		if($validateAjax->isError()){

			$errors = $validateAjax->getErrorMessages();

			echo json_encode($errors);

		}else{

			echo json_encode(array('errors'=>''));
		}

		exit();

		

	}



	if($_GET['validateDescription'] == 1){

		$validateAjax = new ValidateAjax();

		$validateAjax->validateDescription($_POST['txtDescription'], array( 'validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả'));

		if($validateAjax->isError()){

			$errors = $validateAjax->getErrorMessages();

			echo json_encode($errors);

		}else{

			echo json_encode(array('errors'=>''));

			

		}

		exit();

	}



	

	if($_GET['validateGetStory'] == 1){

		header("Cache-Control: no-cache, must-revalidate");

		$validateAjax = new ValidateAjax();

		$validateAjax->validateTitle($_POST['txtTitle']);

		$validateAjax->validateDescription($_POST['txtDescription'], array('validateAlias'=>'txtDescription', 'validateDescription' => 'Mô tả truyện'));

		

		$story = $validateAjax->validateStorySource($_POST['txtSourceUrl'], $_POST['txtSource']);

		

		if($story instanceof sstruyen){

			$class = '1';

			$getlink_start = 0;

		}



		if($story instanceof webtruyen){

			$class = '2';

			$getlink_start = 1;

		}



		if($story instanceof tunghoanh){

			$class = '3';

			$getlink_start = 1;

		}



		if($validateAjax->isError()){

			$errors = $validateAjax->getErrorMessages();

			echo json_encode($errors);

			exit();

		}else{

			// Insert story to database

			$model = new Model();

			$dataInsert = array(

					'ten'				=>	$_POST['txtTitle'],

					'alias' 			=> khongdau(khongdau($_POST['txtTitle'])),

					'tacgia'			=> $_POST['txtAuthor'],

					'tongsochuong'		=> $_POST['txtChaptNums'],

					'gioithieu'			=> $_POST['txtDescription'],

					'time_upload'		=> date('Y-m-d H:i:s'),

					'user_upload'		=> 'millertime',

					'getlink_type'		=> $class,

					'getlink_source'	=> $_POST['txtSourceUrl'],

					'getlink_start'		=> $getlink_start,

					'getlink_auto'		=> $_POST['txtAutoScan'],

			);

			$model->insert('truyen', $dataInsert);

			echo json_encode(array('message' => 'Nhập truyện thành công', 'url' => $story->patternUrl , 'startPage' => $story->startPage, 'story_id' => $idStory));

			exit();

		}

	}

	

	if($_GET['validateGetChapter'] == 1){

		$story = storyfactory::create($_POST['txtSource']);

		$returnLinks = $story->getChapters($_POST['txtSourceUrl'], $_POST['truyenId']);

		if($returnLinks == 'het'){

			echo 'het';

		}else if(is_array($returnLinks)){

			$a = json_encode($returnLinks);

			echo $a;

		}else{

			echo 'Not specific';

		}

		exit();

	}

	

	if($_GET['updateStorySource']==1){
		$story = storyfactory::create($_POST['txtSource']);
		$id = $_POST['storyId'];
		echo $id . '<br />';
		$returnLinks = $story->updateStorySource($id, $_POST['txtLink']);
	}

	

	if($_GET['insertChapter'] == 1){
		$links = json_decode($_POST['links'],true);
		$storyData = $_POST['storyData'];
		$model = new Model();
		echo '<pre>';
		print_r($links);
		echo '</pre>';
		foreach($links as $key => $value){

			if($value['title'] == 'Error' || $value['href'] == 'Error'){
				$is_finish = 0;
			}else{
				$is_finish = 1;

			}

			$dataInsert = array(
					'link' => $value['link'], 
					'title' => html_entity_decode($value['title'],ENT_QUOTES,"UTF-8"),
					'story_id' => $storyData['story_id'], 
					'page'=>$storyData['startPage'],
					'thutu'=>$value['chapt'],
					'tap'=>$value['tap'],
					'is_finish'	=> $is_finish,

			);

			if($value['title'] != 'linkLastInDOM'){
			$model->insert('truyen_chuong_link', $dataInsert);
				if(!$links[$key + 1]){
					$model->where = "id = '" . $storyData['story_id'] . "'";
					$dataLast = array('getlink_last'=>$value['link'], 'getlink_page'=>$storyData['startPage'], 'getlink_last_name'=> $value['title']);
					$model->update('truyen', $dataLast);
				}
			}

		}
		//echo 'here';
		exit();
}

	
	if($_GET['hasNotInsertChapterContent'] == 1){
		$storyId = $_POST['story_id'];
		
		if(!isset($storyId) || empty($storyId)){
			echo json_encode(array('error'=>'Nhập truyện cần lấy nội dung!!!'));
		}
		
		
		$model = new Model();
		$model->select = 'id,ten,getlink_type';
		$model->where = "id = '" . $storyId . "'";
		$model->getdata('truyen');
		$result = $model->fetchOne();
		
		if(!$result){
			echo json_encode(array('error'=>'Truyện không tồn tại nhé'));
		}
		
		$model->select = "id";
		$model->where = "story_id ='" . $result['id'] . "' AND get_content = 0";
		$model->order = "thutu ASC";
		$model->getdata('truyen_chuong_link');
		$resultChapters = $model->fetchOne();
		
		if(!$resultChapters){
			echo '0';
			exit();
		}
		
		echo '1';
		exit();
		
		
	}
	
	
	if($_GET['receivePhantomContent'] == 1){
		file_put_contents('abc.txt', 'abc');
		$link = $_POST['filename'];
		file_put_contents('public/phantom/' . md5($link), $link);
		exit();
	}
	
	
	/*
	 * Lấy truyện chương link trong table truyen_chuong_link (của các link chưa lấy content)
	 * và bắt đầu lấy content sử dụng phantomjs
	 * 
	 */

	if($_GET['requestSubmitStoryChaptersViaPhantom'] == 1){
		
		$linksPerRequest = 100;
		
		$story = $_POST['story_id'];
	
		$model = new Model();
		$model->select = 'id,ten,getlink_type';
		$model->where = "id = '" . $story . "'";
		$model->getdata('truyen');
		$result = $model->fetchOne();
		
		$model->select = "COUNT(id) as countSum";
		$model->where = "story_id ='" . $result['id'] . "' AND put_file = 0";
		$model->getdata('truyen_chuong_link');
		$countResult = $model->fetchOne();
		
		switch($result['getlink_type']){
			case 3:
				$arraySource['alias'] = 'tunghoanh';
				break;
		}
		
		
		$countNum = ceil($countResult['countSum'] / $linksPerRequest);
		
		for($ii = 1; $ii <= $countNum; $ii++){
			$model->select = "id, link, tap, thutu, story_id";
			$model->where = "story_id ='" . $result['id'] . "' AND put_file = 0";
			$model->order = "thutu ASC";
			$model->limit = $linksPerRequest;
			$model->getdata('truyen_chuong_link');
			$resultChapters = $model->fetchAll();
			
			$story = storyfactory::create($result['getlink_type']);
			
			$story->getChapterContentToFiles($resultChapters, $arraySource); // Lấy nội dung của các chapters đưa vào các file trên server
			foreach($resultChapters as $key => $value){
				$model->where = "id = '" . $value['id'] . "'";
				$model->update('truyen_chuong_link', array('put_file'=>1));
			}
		}
		
		
		
		/*
		 * Sau khi lấy tất cả nội dung đưa vào file, lúc này bắt đầu 
		 * lặp tất cả link từ truyen_chuong_link để lấy nội dung từ từng file và đưa vào 
		 * table truyen_chuong và truyen_chuong_noidung
		 */
		$model->select = "id, link, tap, thutu, story_id";
		$model->where = "story_id ='" . $result['id'] . "' AND put_file = 1 AND get_content = 0";
		$model->order = "thutu ASC";
		$model->limit = '';
		$model->getdata('truyen_chuong_link');
		$resultAllChapters = $model->fetchAll();
		
		if($resultAllChapters){
			foreach($resultAllChapters as $key => $value){
				$truyenId = $result['id'];
				$url = 'http://mong.vn/abc.php';
				$surl="receiveChapterContent=1&sourceAlias=".$arraySource['alias']."&id=".$value['story_id'] . "&chapt=" . $value['thutu'];
				$resultContent = mycurl($surl,$url);
				
				if($resultContent){
					$resultContent = json_decode($resultContent, true);
			
					if(isset($resultContent['error'])){
						echo json_encode(array('error' => $resultContent['error']));
					}else{
						$itemExplode = explode('###', $resultContent[0]);

				
						/*  
						 * $_POST['tap'] . '###' .
						 $_POST['truyen_id'] . '###' .
						$_POST['is_image'] . '###' .
						$_POST['image_get'] . '###' .
						$_POST['chapt'] . "###".
						$_POST['title'] . '###' .
						$_POST['content'] . '###' .
						$_POST['truyen_chuong_link_id'] . '###' .
						$_POST['trangthai']
						*/
				
						$dataContent = array(
								'ten'=>$itemExplode[5],
								'alias'=>khongdau(khongdau($itemExplode[5])),
								'noidung'=>'',
								'thutu'=> $itemExplode[4],
								'trangthai'	=> 1,
								'truyen_id' => $itemExplode[1],
								'image'	=> $itemExplode[2],
								'image_get' => $itemExplode[3],
								'truyen_chuong_link_id'	=> $itemExplode[7]
						);
				
						$dataContent['time_upload'] = date('Y-m-d H:i:s');
						$dataContent['user_upload'] = 'mong';
						$model->insert('truyen_chuong', $dataContent);
				
						$contentChapter = $itemExplode[6];
						$pos = strpos($contentChapter, '<img');
						if($pos !== false){
							$is_image = true;
							$image_get = 0;
							$surl="content=".urlencode($contentChapter);
							$url = IMAGE_URL . 'story/story.php';
							$resultContent = mycurl($surl,$url);
							$contentChapter = urldecode($resultContent);
							//$contentChapter = 'Image';
						}else{
							$is_image = false;
							$image_get = 1;
						}
						$resultLastId['id']=$model->get_insert_id();
						$resultLastId['ten']=$dataContent['ten'];
				
						if($resultLastId){
							$dataNoiDung = array('noidung'=> $contentChapter, 'truyen_chuong_id' => $resultLastId['id'], 'truyen_id'=>$dataContent['truyen_id']);
							$model->insert(table_chuong($resultLastId['id']), $dataNoiDung);
				
							if(!$contentChapter){
								$errorChapters[$key]['ten_truyen'] = $result['ten'];
							}
						}
				
						$dataContent['noidung'] = $contentChapter;
						$dataChaptersLink = array('is_finish' => 1, 'image'	=> $dataContent['image'], 'get_content'=>1);
						$model->where = "id = '" . $dataContent['truyen_chuong_link_id'] . "'";
						$model->update('truyen_chuong_link', $dataChaptersLink);
				
						
						$model->where = "id = '" . $dataContent['truyen_id'] . "'";
						$dataUpdateTruyen = array('chuongmoinhat'=>$resultLastId['ten'], 'time_update'=>date('Y-m-d H:i:s'), 'user_update'=>'mong');
						$model->update('truyen', $dataUpdateTruyen);
				
					}
				}
			}
		}
		
		/*
		 *  làm sao insert vào table truyen_chuong và truyen_chuong_noi dung thông qua kết quả từ truyen_chuong_link
		 *  Gửi request lên một file trên server để trả về nội dung của các files chứa nội dung chapter
		 *  Sau đó foreach mảng chứa kết quả để insert vào nội dung
		 */


		if($errorChapters){
			echo json_encode(array('error'=>'Một số chapter không lấy được nội dung.', 'fail_chapters'=>$errorChapters));
			exit();
		}
	
		/*
		 * Delete folder in mong.vn
		 */
		$url = 'http://mong.vn/abc.php';
		$surl= "deleteSourceFolder=1&sourceAlias=" . $arraySource['alias'] . "&id=".$truyenId;
		$resultContent = mycurl($surl,$url);
	
		echo '1';
		exit();
	
	}
	

	if($_GET['requestSubmitStoryChapters'] == 1){
		
		$story = $_POST['story_id'];
		
		$model = new Model();
		$model->select = 'id,ten,getlink_type';
		$model->where = "id = '" . $story . "'";
		$model->getdata('truyen');
		$result = $model->fetchOne();
		
		$model->select = "*";
		$model->where = "story_id ='" . $result['id'] . "' AND get_content = 0";
		$model->order = "thutu ASC";
		$model->limit = "100";
		$model->getdata('truyen_chuong_link');
		
		$resultChapters = $model->fetchAll();

		$story = storyfactory::create($result['getlink_type']);
		
		foreach($resultChapters as $key => $value){
			$contentChapter = $story->getChapterContent($value['link']);
			$pos = strpos($contentChapter, '<img');
			if($pos !== false){
				$is_image = true;
				$image_get = 0;
				$surl="content=".urlencode($contentChapter);
				$url = IMAGE_URL . 'story/story.php';
				$resultContent = mycurl($surl,$url);
				$contentChapter = urldecode($resultContent);
				//$contentChapter = 'Image';
			}else{
				$is_image = false;
				$image_get = 1;
			}

			$str = '504 Gateway Time-out';
			$_504_time_out =  mb_strpos($contentChapter, $str);

				if(!$contentChapter || $_504_time_out !== false){
				$dataContent = array(
					'ten'=>$value['title'],
					'alias'=>khongdau(khongdau($value['title'])),
					'noidung'=>'',
					'thutu'=> $value['thutu'],
					'trangthai'	=> 0,
					'truyen_id' => $value['story_id'],
					'image'	=> '0',
					'image_get' => 1,
					'truyen_chuong_link_id'	=> $value['id']
					);

				$errorChapters[$key] = $dataContent;
			
			}else{


				$dataContent = array(
					'ten'=>$value['title'],
					'alias'=>khongdau(khongdau($value['title'])),
					//'noidung'=>$contentChapter,
					'thutu'=> $value['thutu'],
					'trangthai'	=> 1,
					'truyen_id' => $value['story_id'],
					'image'	=> $is_image,
					'image_get'	=> $image_get,
					'truyen_chuong_link_id'	=> $value['id'],
					);

			}

			

			$dataContent['time_upload'] = date('Y-m-d H:i:s');
			$dataContent['user_upload'] = 'mong';
			$model->insert('truyen_chuong', $dataContent);
			
		 	/*
			$model->select = "id, ten";
			$model->where = "truyen_id = '" . $value['story_id'] . "'";
			$model->order = "id DESC";
			$model->limit = "1";
			$model->getdata('truyen_chuong');
			$resultLastId = $model->fetchOne();
			*/
			
			$resultLastId['id']=$model->get_insert_id();
			$resultLastId['ten']=$value['title'];
			if($resultLastId){
				$dataNoiDung = array('noidung'=> $contentChapter, 'truyen_chuong_id' => $resultLastId['id'], 'truyen_id'=>$value['story_id']);
				$model->insert(table_chuong($resultLastId['id']), $dataNoiDung);
					
				
				if(!$contentChapter){
				$errorChapters[$key]['ten_truyen'] = $result['ten'];

				}
			}

			$dataContent['noidung'] = $contentChapter;
			$dataChaptersLink = array('is_finish' => 1, 'image'	=> $is_image, 'get_content'=>1);
			$model->where = "id = '" . $value['id'] . "'";
			$model->update('truyen_chuong_link', $dataChaptersLink);
			$model->where = "id = '" . $value['story_id'] . "'";
			$dataUpdateTruyen = array('chuongmoinhat'=>$resultLastId['ten'], 'time_update'=>date('Y-m-d H:i:s'), 'user_update'=>'mong');
			$model->update('truyen', $dataUpdateTruyen);

		}

		

		if($errorChapters){

			echo json_encode(array('error'=>'Một số chapter không lấy được nội dung.', 'fail_chapters'=>$errorChapters));

			exit();

		}

		

		echo '1';

	}

	

	if($_GET['getStories'] == 1){



		if($_POST['submitScan'] == 1){
			
			$model = new Model();

			$model->select = '*';

			

			if($_GET['manual'] == 1){

				$model->where="getlink_manual = 0 AND getlink_source IS NOT NULL";

				

				$model->limit = LIMIT_GET_STORY;

			}else{

				$model->where = "getlink_auto = 1";



				$model->limit = LIMIT_GET_STORY;



			}

			

			$model->order = 'id ASC';

			

			$model->getdata('truyen');

			$resultStories = $model->fetchAll();
			
			

			if($resultStories){

				foreach($resultStories as $key => $value){

				

					$story = storyfactory::create($value['getlink_type']);

					

					if($story instanceof sstruyen){

						$resultStories[$key]['pattern_url'] = preg_replace('/.html/', '/page-%s%.html#chaplist', $value['getlink_source']);



					}

					

					if($story instanceof webtruyen){

						$resultStories[$key]['pattern_url'] = $value['getlink_source'] . '%s%';



					}

					

					if($story instanceof tunghoanh){

						$resultStories[$key]['pattern_url'] = $value['getlink_source'] . '%s%';

					}

					

				}

				

				echo json_encode($resultStories);

				exit();

			}else{

				echo '0';

			}

		}

	}

	

	if($_GET['getUnknowStorySource'] == 1){

			$model = new Model();

			$model->where = "nguon IS NULL";

			$model->order = 'id ASC';

			$model->getdata('truyen');

			$resultStories = $model->fetchAll();



			if($resultStories){

				foreach($resultStories as $key => $value){

						

					$story = storyfactory::create($value['getlink_type']);

						

					if($story instanceof sstruyen){

						$resultStories[$key]['pattern_url'] = preg_replace('/.html/', '/page-%s%.html#chaplist', $value['getlink_source']);

	

					}

						

					if($story instanceof webtruyen){

						$resultStories[$key]['pattern_url'] = $value['getlink_source'] . '%s%';

	

					}

						

					if($story instanceof tunghoanh){

						$resultStories[$key]['pattern_url'] = $value['getlink_source'] . '%s%';

					}

						

				}

	

				echo json_encode($resultStories);

				exit();

			}else{

				echo '0';

			}

		

	}

	

	if($_GET['autoScanLinks'] == 1){

		

		if(!$_POST['dataStory']){

			echo 'error_story';

			exit();

		}else{

			$dataStory = $_POST['dataStory'];

			$story = storyfactory::create($dataStory['getlink_type']);

			//$returnLinks = $story->getChapters($_POST['txtSourceUrl']);

			$returnAutoChapters = $story->autoGetChapters($dataStory);



			if($returnAutoChapters == 'het'){

				echo 'het';

			}else if(is_array($returnAutoChapters)){

				$a = json_encode($returnAutoChapters);

				echo $a;

			}else{

				echo 'Not specific';

			}

			exit();

		}

		

		exit();

		

		//$model = new Model();

		//$model->select = '*';

		//$model->where = "story_id = '" . $dataStory['id'] . "'";

		//$model->where

	}

	

	/*

	 * Update where getlink_manual = 0 to 1

	 * Bỏ session của thứ tự

	 */

	if($_GET['updateStoryManualStatus'] == 1){

		

		unset($_SESSION['chapts']);

		unset($_SESSION['tap']);

		unset($_SESSION['chapt']);

		unset($_SESSION['last_chapt']);

		

		$model = new Model();

		$data = array('getlink_manual'=>1);

		$model->where = "id = '" . $_POST['story_id'] . "'";

		$model->update('truyen', $data);

		

		exec('rm -rf ' . MONG_PATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'truyen' . DIRECTORY_SEPARATOR . $_POST['story_id']);

		

		echo 1;

		exit();

	}

	

	if($_GET['removeAutoScan'] == 1){

		$model = new Model();

		$data=array('getlink_auto'=>0);

		$model->where = "id = '" . $_POST['story_id'] . "'";

		$model->update('truyen', $data);

		exec('rm -rf ' . MONG_PATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'truyen' . DIRECTORY_SEPARATOR . $_POST['story_id']);

		echo 1;

		exit();

	}



}









